import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Upload,
  Modal,
  Switch,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { POINT_CONVERSION_COMPRESSED } from 'constants';
import maps from 'qqmap';
import { router } from 'umi';
const FormItem = Form.Item;

const { TextArea } = Input;
const { Search } = Input;
@connect(({ user, shops, loading }) => ({
  user,
  shops,
  submitting: loading.effects['shops/submitShopForm'],
}))
@Form.create()
class BasicForms extends PureComponent {
  state = {
    uploading: false,
    previewVisible: false,
    previewImage: '',
    fileList: [],
    mapModal: false,
    address: '湖北省宜昌市伍家岗区夷陵大道188号',
    latitude: 30.680403,
    longitude: 111.308101,
  };
  showMapModal = () => {
    this.setState({
      mapModal: true,
    });
    this.initQQMap();
  };
  handleOk = e => {
    const { address, latitude, longitude } = this.state;
    const { shops = {}, dispatch } = this.props;
    const { shopSortDetail } = shops;
    shopSortDetail.shop_address = address;
    shopSortDetail.shop_location = JSON.stringify([latitude, longitude]);
    dispatch({
      type: 'shop/fetchShopSortdetail',
      payload: shopSortDetail,
    });
    this.setState({
      mapModal: false,
    });
  };

  handleCancelMap = e => {
    this.setState({
      mapModal: false,
    });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handleChange = ({ fileList }) => this.setState({ fileList });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  uploadPhoto = () => {
    const { fileList } = this.state;
    const { dispatch } = this.props;
    const formData = new FormData();
    formData.append('picture', fileList[fileList.length - 1]);
    dispatch({
      type: 'shops/uploadShopPhoto',
      payload: formData,
      callback: (status, url) => {
        console.log(status);
        if (status === 'success') {
          fileList[fileList.length - 1].url = url;
          console.log(fileList);
          this.setState({
            fileList: fileList,
          });
        } else {
          fileList.pop();
          this.setState({
            fileList: fileList,
          });
        }
      },
    });
  };

  componentDidMount() {
    const { fileList } = this.state;
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'shops/fetchShopSortdetail',
      payload: params.id,
      callback: coursel => {
        if (coursel) {
          const imgList = JSON.parse(coursel);
          imgList.forEach((url, index) => {
            fileList.push({
              uid: -index,
              name: url,
              status: 'done',
              url: url,
            });

            this.setState({ fileList: [...fileList] });
            console.log(this.state.fileList);
          });
        }
      },
    });
  }

  handleSubmit = e => {
    const { fileList } = this.state;
    const { shops = {}, dispatch, form } = this.props;
    const { shopSortDetail = {} } = shops;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      console.log(values);
      if (!err) {
        let coursel = [];
        fileList.forEach((item, index) => {
          coursel.push(item.url);
        });
        values.img = JSON.stringify(coursel);
        values.id = shopSortDetail.id;
        dispatch({
          type: 'shops/submitShopSortUpateForm',
          payload: values,
          callback() {
            router.push('/shoplist/sort-list');
          },
        });
      }
    });
  };

  beforeUpload = file => {
    this.setState(state => ({
      fileList: [...state.fileList, file],
    }));
  };

  render() {
    const { previewVisible, previewImage, fileList, address } = this.state;
    const { shops = {}, submitting } = this.props;
    const { shopSortDetail = {} } = shops;
    const {
      form: { getFieldDecorator },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );

    return (
      <PageHeaderWrapper title={<FormattedMessage id="menu.shoplist.addshop" />}>
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.sortimg' })}>
              <Upload
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
                customRequest={this.uploadPhoto}
                beforeUpload={this.beforeUpload}
              >
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </FormItem>

            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.sortname' })}>
              {getFieldDecorator('title', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'shop.sortname.placeholder' }),
                  },
                ],
                initialValue: shopSortDetail.title,
              })(<Input placeholder={formatMessage({ id: 'shop.sortname.placeholder' })} />)}
            </FormItem>

            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.isshow' })}>
              {getFieldDecorator('status', {
                initialValue: shopSortDetail.status,
              })(<Switch defaultChecked />)}
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                <FormattedMessage id="form.save" />
              </Button>
            </FormItem>
          </Form>
          <Modal
            title="选择地址"
            visible={this.state.mapModal}
            onOk={this.handleOk}
            onCancel={this.handleCancelMap}
            width="80%"
          >
            <div>
              <p>当前位置：{address}</p>
            </div>
            <div id="container" style={{ height: 600 }} />
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default BasicForms;
